package com.btcode.json;

import com.btcode.common.AbstractSingleton;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import java.io.StringReader;
import java.sql.Clob;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class JsonConver extends AbstractSingleton implements IJsonConver {

    private Gson gson;

    public JsonConver() {
        gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").registerTypeAdapter(
            Clob.class, new SqlClobAdapter()).create();
    }

    public String toJson(Object data) {
        String json = gson.toJson(data);
        return json;
    }

    public <T> Map<String, T> JsonToMaps(String gsonString) {
        Map<String, T> map = null;
        if (gson != null) {
            map = gson.fromJson(gsonString, new TypeToken<Map<String, T>>() {
            }.getType());
        }
        return map;
    }

    public <T> List<T> JsonToList(String gsonString, Class<T> cls) {
        List<T> list = new ArrayList<>();
        JsonArray jsonArray = new JsonParser().parse(gsonString).getAsJsonArray();

        for (JsonElement jsonElement : jsonArray) {
            list.add(gson.fromJson(jsonElement,cls)); //cls
        }

        return list;
    }

    public <T> T JsonToObject(String gsonString, Class<T> cls) {
        T object ;
        JsonReader reader = new JsonReader(new StringReader(gsonString));
        reader.setLenient(true);
        object = gson.fromJson(reader, cls);
        return object;
    }

    public JsonObject jsonToJsonObject(String gsonString){
       return new JsonParser().parse(gsonString).getAsJsonObject();
    }

}
